<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import { Login } from '@/api/login';
import { setToken } from '../store';
import router from '@/router';
import { getUserInfo } from '@/api/userInfo';

interface account {
  userName: string,
  passWord: string
}

const userAccount = ref<account>({
  userName: '',
  passWord: ''
})


function login(){
  userAccount.value.userName = userAccount.value.userName.toLocaleLowerCase()
  let domain: string = userAccount.value.userName.substring(0,7);
  
  if(userAccount.value.userName.length <= 7){
    ElMessage.error("賬號輸入格式不正確")
    return false
  }
  else if (domain !== "xdomain" && domain !== "pdomain" && domain != "qdomain" && domain !== "sdomain"){
    ElMessage.error("賬號格式不正確")
    return false
  }

  if(userAccount.value.passWord === ""){
    ElMessage.error("密碼不能為空")
    return false
  }

  let userName = userAccount.value.userName
  let passWord = userAccount.value.passWord
  Login(userName,passWord).then((res:any)=>{
    if(res){
      //將token加入狀態管理
      setToken(res.toString())
      ElMessage({
        type:'success',
        message:"登錄成功",
        offset:20
      })
      //將用戶賬號等信息存入localstorage
      localStorage.setItem('username',userAccount.value.userName)
      getUserInfo(userAccount.value.userName).then((res:any) => {
         localStorage.setItem('name',res[0].chinese_name)
         localStorage.setItem('dept',res[0].dept)
         localStorage.setItem('worknum',res[0].work_num)
         router.push('/home')
      })    
    }
  })

}


</script>

<template>
  <div class="loginBox">
    <el-container>
      <el-main class="Login-main">
        <div class="user">
          <el-input v-model.lzay="userAccount.userName" style="width: 240px;" placeholder="请输入账号" :prefix-icon="User" />
        </div>
        <div class="password">
          <el-input v-model="userAccount.passWord" style="width: 240px;" placeholder="请输入密码" type="password" :prefix-icon="Lock" />
        </div>
        <div class="confirm">
          <el-button type="primary" color="#626aef" style="font-weight: bold;font-size: 15px;color: #000;width:240px" @click="login">登录</el-button>
        </div>
      </el-main>
      <el-footer>

      </el-footer>
    </el-container>
  </div>
</template>


<style>
.loginBox {
  width: 100%;
  height: 100%;
  background-color: #545c64;
  margin: auto;
  /* padding-top: 100px; */
}

.Login-main {
  margin: 150px auto;
  background-color: rgba(255, 255, 255, 0.226);
  width: 500px;
  height: 350px;
  border-radius: 20px;
  padding-top: 7em;
}

.user,
.password,
.confirm {
  height: 40px;
  line-height: 40px;
  /* padding-left: 30px; */
  opacity: 0.75;
  text-align: center;
  margin-top: 10px;
}
.confirm{
  opacity: 1;
}

</style>